﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Admin.NET.Core.Util;

namespace Admin.NET.Application;
/// <summary>
/// 接收的SocketDatat服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ReceiveDataService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<ReceiveData> _rep;
    private readonly BoardBaseService _boardBaseService;
    private readonly BoardRouteInfoService _boardRouteInfoService;
    public ReceiveDataService(BoardBaseService boardBaseService, BoardRouteInfoService boardRouteInfoService,SqlSugarRepository<ReceiveData> rep)
    {
        _boardBaseService= boardBaseService;
        _boardRouteInfoService= boardRouteInfoService;
        _rep = rep;
    }
    /// <summary>
    /// 分页查询接收的SocketDatat
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<ReceiveDataOutput>> Page(ReceiveDataInput input)
    {
        var query = _rep.AsQueryable()
            .Select<ReceiveDataOutput>();
        if(input.EventTimeRange != null && input.EventTimeRange.Count >0)
        {
            DateTime? start= input.EventTimeRange[0]; 
            query = query.WhereIF(start.HasValue, u => u.EventTime > start);
            if (input.EventTimeRange.Count >1 && input.EventTimeRange[1].HasValue)
            {
                var end = input.EventTimeRange[1].Value.AddDays(1);
                query = query.Where(u => u.EventTime < end);
            }
        } 
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加接收的SocketDatat
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddReceiveDataInput input)
    {
        var entity = input.Adapt<ReceiveData>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除接收的SocketDatat
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteReceiveDataInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
        //await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新接收的SocketDatat
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateReceiveDataInput input)
    {
        var entity = input.Adapt<ReceiveData>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取接收的SocketDatat
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<ReceiveData> Detail([FromQuery] QueryByIdReceiveDataInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取接收的SocketDatat列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<ReceiveDataOutput>> List([FromQuery] ReceiveDataInput input)
    {
        return await _rep.AsQueryable().Select<ReceiveDataOutput>().ToListAsync();
    }

    /// <summary>
    /// 写入数据
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public long SaveData(byte[] input)
    {
        var entity=SocketUtil.formatData(input);
        var b=_boardBaseService.getBoard(entity.BlindId.ToString());
        if (b == null)
        {
            AddBoardBaseInput nb = new AddBoardBaseInput();
            nb.BoardNo = entity.BlindId.ToString();
            nb.RouteNo = entity.RouteId.ToString();
            nb.BoardState = getBoardState(entity);
            nb.CreateTime = DateTime.Now;
            nb.CreateUserName = "auto";
            _boardBaseService.Add(nb);
        }
        else
        {
            b.BoardState = getBoardState(entity);
            b.UpdateTime = DateTime.Now;
            _boardBaseService.UpdateData(b);
        }
        var r = _boardBaseService.getBoard(entity.BlindId.ToString());
        if (r == null)
        {
            AddBoardRouteInfoInput nb = new AddBoardRouteInfoInput();
            nb.RouteNo = entity.RouteId.ToString();
            _boardRouteInfoService.Add(nb);
        }
        _rep.InsertAsync(entity);
        return entity.Id;
    }

    private string getBoardState(ReceiveData r)
    {
        string rtn = "";
        if (r == null)
        {
            return "9";
        }
        if (String.IsNullOrEmpty(r.Data2))
        {
            return "9";
        }
        char[] k = r.Data2.ToCharArray();
        if (k[1] == '1')//故标识
        {
            return "9";
        }
        if (k[7] == '1')
        {
            return "1";
        }
        else
        {
            return "0";
        }

    }
   

}

